package com.example.stream.controller;

import com.example.stream.entity.PredictionEntity;
import com.example.stream.entity.User;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@RestController
public class IndexController {
    @PostMapping("/stream")
    public ResponseEntity<StreamingResponseBody> stream() {
        StreamingResponseBody stream = out -> {
            System.out.println("start");
            try {
                Thread.sleep(10 * 1000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("end");
            out.write(("This is line " + 3 + "\n").getBytes());
            out.flush();
//            for (int i = 0; i < 10; i++) {
//                try {
//                    Thread.sleep(1000);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//                System.out.println(i);
//                out.write(("This is line " + i + "\n").getBytes());
//                out.flush();
//            }
        };
        return ResponseEntity.ok().contentType(MediaType.TEXT_PLAIN).body(stream);
    }

    @GetMapping("/sse-endpoint")
    public SseEmitter streamEvents() {
        SseEmitter emitter = new SseEmitter();

        Executors.newSingleThreadExecutor().execute(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    emitter.send(SseEmitter.event().data("Hello, SSE! " + i));
                    TimeUnit.SECONDS.sleep(1);
                }
                emitter.complete();
            } catch (IOException | InterruptedException e) {
                emitter.completeWithError(e);
            }
        });

        return emitter;
    }

    @PostMapping("/stream2")
    public User stream2(@RequestBody PredictionEntity entity) {
        System.out.println(Thread.currentThread().getId());
        System.out.println("start");
        try {
            Thread.sleep(1 * 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("end");
        return new User(1, "张三", "张三三", "123456", 1, 2);
    }
}
